package com.etrans.web.gps.business.report.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.report.domain.TourismViolationVO;
import com.etrans.web.gps.common.MGTemplete;
import com.etrans.web.gps.util.Config;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.FindIterable;

/**
 * @author zhang
 * @ClassName:  RegionalStatisticsService  
 */
@Service
public class TourismViolationService extends BaseService{

	@Autowired
	private Config config; //引用统一的参数配置类 
	
	private final static String V_TABLE = "tourist_vehicle_exception";
	
	private final static String E_TABLE = "tourist_vehicle_exception_enterprise";
	/**
	 * 查询登录用户权限下的全部的旅游车辆
	 * @param area_id 区域编号   
	 * trade_kind_id 旅游客运类型编号 为  2
	 * @return  车辆所有信息
	 */
	public List<HashMap<String, Object>> queryVeListByRoleAndKind(Integer area_id,String vehicle_no) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("trade_kind_id", 2);
		param.put("FullID", String.format("%08d",area_id));
		param.put("vehicle_no", vehicle_no);
		return  selectList("tourismViolation.queryVeListByRoleAndKind", param);
	}

	/**
	 * 查询登录用户权限下的所有业户
	 * @return  业户信息列表
	 */
	public List<HashMap<String,Object>> queryEnterAndPlatByRole(int areaId,String name){
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",areaId));
		param.put("name", name);
		param.put("selected", "selected");
		return  this.selectList("tourismViolation.queryEnterAndPlatByRole",param);
	}


	/**
	 * 查询登录用户权限下的所有业户的ID
	 * @return  业户信息列表
	 */
	public List<Integer> queryEnterIdListByRole(int areaId){
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("FullID", String.format("%08d",areaId));
		return  this.selectList("tourismViolation.queryEnterIdListByRole",param);
	}

	/**
	 * 根据查询条件查询
	 * @param areaId
	 * @param startTime
	 * @param endTime
	 * @param queryType
	 * @param queryContent
	 * @return 获取柱状图查询数据
	 * @throws Exception
	 */
	public Map<String, Object> queryBarChartData(int areaId, String startTime, String endTime, String queryType,
			String queryContent) throws Exception{
		//过滤条件
        DBObject match = new BasicDBObject();
        //时间条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = sdf.parse(startTime+" 00:00:00");
        Date endDate = sdf.parse(endTime+" 23:59:59");
        match.put("analyse_date", new BasicDBObject("$gte", startDate).append("$lte", endDate));
        if (StringUtils.isNotBlank(queryContent)) {
			if ("ent".equals(queryType)) {
				match.put("enterprise_name", queryContent);
			}else if ("veh".equals(queryType)) {
				match.put("vehicle_no", queryContent);
			}
		}else {
			match.put("enterprise_id", new BasicDBObject("$in", this.queryEnterIdListByRole(areaId)));
		}
        //分组
		DBObject group = new BasicDBObject("_id", "$enterprise_id");
		group.put("count", new BasicDBObject("$sum", 1));
		group.put("enterprise_name", new BasicDBObject("$first", "$enterprise_name"));
		//聚合参数
		List<Bson> bson = new ArrayList<Bson>();
		bson.add(new BasicDBObject("$match", match));
		bson.add(new BasicDBObject("$group", group));
		AggregateIterable<Document> documents = MGTemplete.getCollection(DBNAME, V_TABLE).aggregate(bson);
		List<String>  xAxisData =new ArrayList<String>();
		List<Integer>  SeriesData =new ArrayList<Integer>();
		List<Integer>  ids =new ArrayList<Integer>();
		for (Document doc : documents) {
			xAxisData.add(doc.getString("enterprise_name"));
			SeriesData.add(doc.getInteger("count"));
			ids.add(doc.getInteger("_id"));
		}
		Map<String,Object> map =new HashMap<String, Object>();
		map.put("bar_series", SeriesData);
		map.put("bar_xAxisData", xAxisData);
		map.put("ids", ids);
		map.put("address_Path", config.addressPath);
		return map;
	}

	/**
	 * 根据业户id和查询时间
	 * @return 单个业户一天24小时的异动车辆数量
	 * @param startTime
	 * @param endTime
	 * @param enterprise
	 * @throws ParseException 
	 */
	public Map<String, Object> queryLineChartData(String startTime, String endTime, String enterprise) 
			throws Exception {
		//过滤条件
		BasicDBObject query = new BasicDBObject();
        query.put("enterprise_name", enterprise);
        //时间条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = sdf.parse(startTime+" 00:00:00");
        Date endDate = sdf.parse(endTime+" 23:59:59");
        query.put("analyse_date", new BasicDBObject("$gte", startDate).append("$lte", endDate));
        Bson filter = new BasicDBObject(query);
		FindIterable<Document> documents = MGTemplete.getCollection(DBNAME, E_TABLE).find(filter);
		List<Integer> SeriesData =new ArrayList<>();
		for (int i = 0; i < 24; i++) {
			SeriesData.add(0);
		}
		for (Document doc : documents) {
			Document exceptionList = (Document) doc.get("exception_list");
			for (int i = 0; i < SeriesData.size(); i++) {
				SeriesData.set(i, SeriesData.get(i) + exceptionList.getInteger("count"+i, 0));
			}
		}
		List<String>  xAxisData =new ArrayList<>();
		for (int i = 0; i < 24; i++) {
			xAxisData.add(i+":00");
		}
		Map<String,Object> map =new HashMap<String, Object>();
		map.put("line_series", SeriesData);
		map.put("line_xAxisData", xAxisData);
		return map;
	}

	/**
	 * 根据查询条件查询明细总数
	 * @param areaId
	 * @param startTime
	 * @param endTime
	 * @param queryType
	 * @param queryContent
	 * @return
	 * @throws Exception 
	 */
	public Integer queryTourismTableCount(int areaId, String startTime, String endTime, String queryType,
			String queryContent) throws Exception {
		//过滤条件
		BasicDBObject query = new BasicDBObject();
        //时间条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = sdf.parse(startTime+" 00:00:00");
        Date endDate = sdf.parse(endTime+" 23:59:59");
        query.put("analyse_date", new BasicDBObject("$gte", startDate).append("$lte", endDate));
        if (StringUtils.isNotBlank(queryContent)) {
			if ("ent".equals(queryType)) {
				query.put("enterprise_name", queryContent);
			}else if ("veh".equals(queryType)) {
				query.put("vehicle_no", queryContent);
			}
		}else {
			query.put("enterprise_id", new BasicDBObject("$in", this.queryEnterIdListByRole(areaId)));
		}
        Bson filter = new BasicDBObject(query);
		Long count = MGTemplete.getCollection(DBNAME, V_TABLE).count(filter);
		return count.intValue();
	}

	/**
	 * 分页查询
	 * @param areaId
	 * @param startTime
	 * @param endTime
	 * @param queryType
	 * @param queryContent
	 * @param page
	 * @param size
	 * @return
	 * @throws Exception 
	 */
	public List<TourismViolationVO> queryTourismTable(int areaId, String startTime, String endTime, String queryType,
			String queryContent, int from, int size) throws Exception {
		//过滤条件
		BasicDBObject query = new BasicDBObject();
        //时间条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = sdf.parse(startTime+" 00:00:00");
        Date endDate = sdf.parse(endTime+" 23:59:59");
        query.put("analyse_date", new BasicDBObject("$gte", startDate).append("$lte", endDate));
        if (StringUtils.isNotBlank(queryContent)) {
			if ("ent".equals(queryType)) {
				query.put("enterprise_name", queryContent);
			}else if ("veh".equals(queryType)) {
				query.put("vehicle_no", queryContent);
			}
		}else {
			query.put("enterprise_id", new BasicDBObject("$in", this.queryEnterIdListByRole(areaId)));
		}
        Bson filter = new BasicDBObject(query);
        Bson sort = new BasicDBObject("vehicle_no", 1).append("gps_time", -1);
		FindIterable<Document> documents = 
				MGTemplete.getCollection(DBNAME, V_TABLE).find(filter).sort(sort).skip(from).limit(size);
		List<TourismViolationVO> list = new ArrayList<>();
		for (Document doc : documents) {
			list.add(toBean(doc, TourismViolationVO.class));
		}
		return list;
	}

	/**
	 * 
	 * @param document
	 * @param clazz
	 * @return
	 */
	public static <T> T toBean(Document document, Class<T> clazz) {
        String json = JSONObject.toJSONString(document);
        return JSONObject.toJavaObject(JSONObject.parseObject(json), clazz);
    }
}
